<!--
 * @Author: Damon Liu
 * @Date: 2025-04-27 14:35:15
 * @LastEditors: Damon Liu
 * @LastEditTime: 2025-04-29 17:45:26
 * @Description:  基于fullcalendar的日历组件
-->
<template>
    <div>
        <FullCalendar ref="calendarRef" class='appointment-calendar' :options="calendarOptions">
            <template v-slot:eventContent='arg'>
                <a-tooltip :title="arg.event.extendedProps.description">
                    <div style="height: 100%; overflow: hidden;">
                        <div class="fc-event-title">
                            <span>{{ arg.event.title }}</span>
                        </div>
                        <div v-if="arg.event.extendedProps.description">
                            {{ arg.event.extendedProps.description }}
                        </div>
                        <div class="fc-event-time">
                            <span v-if="arg.event.extendedProps.reminder">
                                <BellOutlined /> {{ formatReminderTime(arg.event.extendedProps.reminder) }}
                            </span>
                        </div>
                    </div>
                </a-tooltip>
            </template>
        </FullCalendar>
        <ScheduleDetailModal ref="scheduleDetailModalRef" />
    </div>
</template>

<script setup>
import FullCalendar from '@fullcalendar/vue3'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import timeGridPlugin from '@fullcalendar/timegrid'
import { onMounted, ref, shallowRef, computed, watch } from 'vue';
import dayjs from 'dayjs';
import { BellOutlined } from '@ant-design/icons-vue';
import ScheduleDetailModal from './scheduleDetailModal.vue';
import { EVENT_TYPES } from '~/utils/enums'
const scheduleDetailModalRef = ref()

const props = defineProps({
    scheduleList: {
        type: Array,
        required: true
    }
})


const calendarRef = shallowRef()

const updateEvents = () => {
    const calendarApi = calendarRef.value?.getApi();
    if (calendarApi) {
        calendarApi.getEvents().forEach(events => {
            events.remove();
        });
        props.scheduleList.forEach(event => {
            calendarApi.addEvent({
                ...event,
                title: event.title,
                start: event.start ? dayjs(event.start).format('YYYY-MM-DD HH:mm:ss') : '',
                end: event.end ? dayjs(event.end).format('YYYY-MM-DD HH:mm:ss') : '',
                backgroundColor: EVENT_TYPES[event.type?.toUpperCase()]?.color || '#1890ff',
                borderColor: EVENT_TYPES[event.type?.toUpperCase()]?.color || '#1890ff'
            })
        })
    }
}

watch(props.scheduleList, () => {
    updateEvents();
}, { deep: true })

onMounted(() => {
    updateEvents();
})

const emit = defineEmits(['dateSet'])

const setCalendarRange = (start, end) => {
    const calendarApi = calendarRef.value?.getApi();
    if (calendarApi && start) {
        // 跳转到 start 日期所在的视图
        // 这里以周视图为例，可根据 initialView 动态调整
        calendarApi.changeView('timeGridWeek', start);
    }
}

defineExpose({
    updateEvents,
    setCalendarRange,
})

const handleDateSet = (info) => {
    emit('dateSet', info)
}

// 格式化提醒时间
const formatReminderTime = (reminder) => {
    if (!reminder) return '';
    return dayjs(reminder).format('HH:mm');
}

const calendarOptions = ref({
    events: [],
    slotDuration: `00:05:00`,
    locale: 'zh-cn',
    allDayText: "全天",
    nowIndicator: true,
    allDaySlot: false,
    buttonText: {
        today: '今天',
        month: '月视图',
        week: "周",
        day: '日视图',
    },
    // 隐藏头部的 prev/next 按钮
    headerToolbar: {
        left: '',
        //center: 'title',
        center: '',
        right: ''
    },
    plugins: [
        dayGridPlugin,
        timeGridPlugin,
        interactionPlugin // needed for dateClick
    ],
    initialView: 'timeGridWeek',
    initialEvents: [], // alternatively, use the `events` setting to fetch from a feed
    selectable: false,       // 是否可以选择
    selectMirror: true,     // 选择的时候在原地产生一个镜像
    dayMaxEvents: true,
    scrollTime: new Date().toLocaleTimeString(),
    editable: false,
    firstDay: 1,
    weekends: true,
    dateClick: handleDateClick,
    datesSet: handleDateSet,
    eventDidMount: (info) => {
        // 根据事件类型设置背景颜色
        const eventType = info.event.extendedProps.type;
        if (eventType) {
            const typeConfig = EVENT_TYPES[eventType.toUpperCase()];
            if (typeConfig) {
                info.el.style.backgroundColor = typeConfig.color;
            }
        }
    },
    events: [],
    eventClick: handleEventClick
})

// 处理日期点击事件
function handleDateClick(arg) {
    // 这里可以添加创建新事件的逻辑
    console.log('date clicked', arg);
}

function handleEventClick(info) {
    scheduleDetailModalRef.value.show(info.event.extendedProps)
}
</script>

<style scoped>
.appointment-calendar {
    height: calc(100vh - 150px);
}
.fc-event-title {
    font-weight: bold;
}

.fc-event-time {
    font-size: 0.8em;
    margin-top: 4px;
}

.icon-bell {
    margin-right: 4px;
}
</style>